package com.zpark;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Locale;

/**
 * 处理表单请求
 */
@WebServlet("/sd2.do")
public class ServletDemo02 extends HttpServlet {
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 请求对象常用方法
		/*
		* getContextPath()：获取虚拟目录（项目访问路径）
		 */
		String path = req.getContextPath();

		/*
		* getSession()：获取HttpSession对象
		 */
		HttpSession session = req.getSession();

		/*
		* getHeaderNames()：获取请求头所有名称
		 */
		Enumeration<String> names = req.getHeaderNames();
		// 循环遍历所有请求头名字
		while (names.hasMoreElements()) {
			// 获取请求头名字
			String name = names.nextElement();
			// 根据名字获取对应的值
			String value = req.getHeader(name);

			System.out.println(name + "=" + value);
		}

		System.out.println("*********************************************************");

		/*
		* getMethod()：获取请求方式
		 */
		String method = req.getMethod();
		System.out.println("请求方式：" + method);

		/*
		* getPathInfo()：获取请求资源路径
		 */
		String pathInfo = req.getPathInfo();
		System.out.println("请求资源路径：" + pathInfo);

		/*
		* getRequestURI()：获取请求资源路径
		 */
		String requestURI = req.getRequestURI();
		System.out.println("请求资源路径：" + requestURI);

		/*
		* getRequestURL()：获取请求资源路径
		 */
		StringBuffer requestURL = req.getRequestURL();
		System.out.println("请求资源路径：" + requestURL);

		/*
		* getLocalAddr()：获取服务器地址
		 */
		String localAddr = req.getLocalAddr();
		System.out.println("服务器地址：" + localAddr);

		/*
		* getLocale()：获取服务器封装对象
		 */
		Locale locale = req.getLocale();

		/*
		* getLocalName()：获取服务器名称
		 */
		String localName = req.getLocalName();
		System.out.println("服务器名称：" + localName);

		/*
		* getLocalPort()：获取服务器端口号
		 */
		int localPort = req.getLocalPort();
		System.out.println("服务器端口号：" + localPort);

		System.out.println("*********************************************************");

		/*
		* getParameter("uname")：根据请求参数名字获取请求参数值
		 */
		String uname = req.getParameter("uname");
		System.out.println("用户名：" + uname);
		String pwd = req.getParameter("pwd");
		System.out.println("密码：" + pwd);
	}

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 获取请求参数
		String uname = req.getParameter("uname");
		String pwd = req.getParameter("pwd");

		String msg = "";
		// 判断用户是否登录成功
		if ("sentinel".equals(uname) && "sentinel".equals(pwd)) {
			msg = "登录成功";
		} else {
			msg = "登录失败，用户名或者密码错误";
		}

		// 将msg绑定到上下应用文作用域
		req.getServletContext().setAttribute("msg", msg);
	}
}
